package com.tensquare.web.filter;

import com.netflix.hystrix.collapser.RequestCollapser;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IDEA
 * author:zhiXiang-Chen
 * Date:2019/3/8
 * Time:22:23
 */
@Component
public class WebFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";       // 前置过滤器
    }

    @Override
    public int filterOrder() {
        return 0;   //优先级为0，数字越大，优先级越低  不能为负数
    }


    @Override
    public boolean shouldFilter() {
        return true;       //否执行该过滤器，此处为true，说明需要过滤
    }

    /**
     * 核心方法 shouldFilter 为true的话  这个方法就会生效
     * 过滤之后要执行的 业务  写在这个方法里面
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        System.out.println("zuul过滤器...");

        //网站前台基本上不需要什么权限过滤,但是经过网关的时候,header会丢失. 我们现在在过滤器中接收header，转发给微服务
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        String authorization = request.getHeader("Authorization");

        if (authorization!=null){
            requestContext.addZuulRequestHeader("Authorization",authorization);
        }

        return null;
    }
}
